# coding=utf-8

# 功能介绍：将命名坏的毕业生登记表修复命名

import os
import xlrd

path = 'C:\\Users\\Administrator\\Desktop\\毕业班毕业生登记表测试'

# 遍历文件夹，获取每个文件的绝对路径
Filelist = []
for home, dirs, files in os.walk(path):
    for filename in files:
        # 文件名列表，包含完整路径
        Filelist.append(os.path.join(home, filename))

# 读取excel
data = xlrd.open_workbook(r'C:\Users\Administrator\Desktop\张莹莹.xls')
# 获取sheet1的行数
sheet1 = data.sheets()[0]
rows = sheet1.nrows

last_name = ""
# j = 1

for file in Filelist:

    # 路径
    # 找到倒数第二个\的位置,从0到该位置获取根路径
    root_path = file[0:int(file.rindex("\\"))]

    # 文件名
    file_name = file[-11:]

    # 学生名称
    student_name = root_path[int(root_path.rindex("\\")):len(root_path)].replace('\\', '', 1)

    # 班级名称
    root_path2 = root_path[0:int(root_path.rindex("\\"))]
    clazz_name = root_path2[int(root_path2.rindex("\\")):len(root_path2)].replace('\\', '', 1)

    # 扩展名
    extension = file[-4:]

    for i in range(rows):
        # 跳过第一行
        if i == 0:
            continue;
        # i行的list
        row = sheet1.row_values(i)
        # 如果班级相同，且学生姓名包含
        if (clazz_name == row[3]) & student_name.__contains__(row[2]):
            # 如果本次的姓名等于上次的姓名
            if row[2] == last_name:
                j = j + 1
            else:
                last_name = row[2]
                j = 1
                # 进入班级文件夹
                os.chdir(r'C:\Users\Administrator\Desktop\毕业班毕业生登记表测试'+"\\"+row[3])
                # 创建大学号+姓名文件夹
                os.mkdir(str(int(row[1])) + row[2])
            # 改名
            os.rename(file, os.path.join(root_path2, str(int(row[1])) + row[2],
                                             str(int(row[1])) + row[2] + "-" + str(j) + extension))
